package springbook.user.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import springbook.user.domain.User;
import springbook.user.domain.User.Level;

public class UserDaoJdbc implements UserDao{

	private RowMapper<User> userMapper = 
		new RowMapper<User>(){	
		public User mapRow(ResultSet rs, int rowNum) throws SQLException{
			User user = new User();
			user.setId(rs.getString("userid"));
			user.setName(rs.getString("name"));
			user.setPassword(rs.getString("password"));
			user.setEmail(rs.getString("email"));
			user.setLevel(Level.valueOf(rs.getInt("Level")));
			user.setLogin(rs.getInt("Login"));
			user.setRecommand(rs.getInt("Recommand"));
			
			return user;
		}
	};
	
	private JdbcTemplate jdbcTemplate;
	
	public void setDataSource(DataSource dataSource) {
		
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public void add(final User user) {
				
		this.jdbcTemplate.update("insert into users(userid, name, password, email, Level, Login, Recommand) values(?,?,?,?,?,?,?)", user.getId(), user.getName(), user.getPassword(), user.getEmail(), user.getLevel().intValue(), user.getLogin(), user.getRecommand());
	}
	
	public User get(String id) {
		
		return this.jdbcTemplate.queryForObject("select * from users where Userid = ?", new Object[] {id},this.userMapper);
	}
	
	public void deleteAll() {
		
		this.jdbcTemplate.update("delete from users");
	}
	
	public int getCount() {
		
		return this.jdbcTemplate.queryForInt("select count(*) from users");
	}	
	
	public List<User> getAll(){
		return this.jdbcTemplate.query("select * from users order by userid", this.userMapper);
	}

	@Override
	public void update(User user1) {
		this.jdbcTemplate.update("update users set name=?, password=?, email = ?, Level=?, Login=?, Recommand=? where userid = ?", user1.getName(), user1.getPassword(), user1.getEmail(), user1.getLevel().intValue(), user1.getLogin(), user1.getRecommand(), user1.getId());		
	}
}
